var util = require("../../utils/util.js");
var api = require("../../config/api.js");
var Map = require("../../utils/map.js");

// 获取地图的返回信息
const chooseLocation = requirePlugin("chooseLocation");

const BACK =
        "http://booking-prod.oss-cn-shenzhen.aliyuncs.com/tata/Leader/id_bg.png",
    POSITIVE =
        "http://booking-prod.oss-cn-shenzhen.aliyuncs.com/tata/Leader/id_country.png";
Page({
    /**
     * 页面的初始数据
     */
    data: {
        // region: ['广东省', '广州市', '海珠区'],
        region: [],
        isClearShow: false,
        // hasStorefront: true,
        // address: data.id,
        back: BACK, //反面身份证
        // hasStorefront: true,
        // lat: 0,
        // leaderName: 0,
        // lon: 0,
        // memberId: 0,
        // phone: 0,
        positive: POSITIVE, //正面身份证
        // username: "",
        // village: "",
        showPhoneValid: false,
        phone: "",
        location: {
            latitude: 0,
            longitude: 0,
        },
        mapName: "",
        mapDetail: "",
        latitude: "",
        longitude: "",
        numTotal: 0,
        // files: [{
        //     url: 'http://mmbiz.qpic.cn/mmbiz_png/VUIF3v9blLsicfV8ysC76e9fZzWgy8YJ2bQO58p43Lib8ncGXmuyibLY7O3hia8sWv25KCibQb7MbJW3Q7xibNzfRN7A/0',
        // }, {
        //     loading: true
        // }, {
        //     error: true
        // }]
        doorPhoto: [],
        storePhoto: [],
        findMerchantCityInfoList: [],
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({
            selectFile: this.selectFile.bind(this),
            uplaodFile: this.uplaodFile.bind(this),
        });
        this.findMerchantCityInfoListData();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        const location = chooseLocation.getLocation();
        if (location) {
            let mapName = location.province + location.city + location.district;

            console.log("location", location);
            if (!mapName) {
                mapName = location.address.split(location.name)[0] || "";
            }
            const mapDetail =
                location.address.split(location.district)[1] + location.name;
            const latitude = location.latitude,
                longitude = location.longitude;
            this.setData({
                location,
                mapName: mapName || "",
                mapDetail: mapDetail || "",
                latitude,
                longitude,
            });
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        chooseLocation.setLocation(null);
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {},
    // 地图事件
    toMap() {
        Map.getAddress(this.data.location);
    },
    // 手机事件 开始
    clearHide: function (e) {
        const value = this.data.phone;
        if (!/^1[0-9]{10}$/.test(value)) {
            this.setData({
                showPhoneValid: true,
            });
        } else {
            if (this.data.showPhoneValid) {
                this.setData({
                    showPhoneValid: false,
                });
            }
        }
        this.setData({
            isClearShow: false,
        });
    },
    clearShow: function (e) {
        this.setData({
            showPhoneValid: false,
            isClearShow: true,
        });
    },
    clearPhone: function (e) {
        this.setData({
            phone: "",
        });
    },
    phoneInput: function (e) {
        this.setData({
            phone: e.detail.value,
        });
    },
    // 手机事件 结束
    // 后台请求
    applyMember(data) {
        wx.showLoading({
            title: "正在提交中",
            icon: "none",
        });
        util.request(api.surroundings.shopCertification, data, "POST")
            .then((res) => {
                console.log("ress", res);
                wx.hideLoading();
                // wx.showToast({
                //     title: res.message,
                //     icon: "none"
                // })
                wx.redirectTo({
                    url: "/Leader/application/application-result/application-result",
                });
            })
            .catch((err) => {
                console.log("err", err);
                wx.hideLoading();
                wx.showToast({
                    title: err.message,
                    icon: "none",
                });
            });
    },
    // 提交表单
    formSubmit: function (e) {
        const result = this.validForm(e.detail.value);
        if (result) {
            // 验证成功
            const data = this.getParams(e.detail.value);
            console.table(data);
            this.applyMember(data);
        }
    },
    // 表单验证
    validForm(values) {
        let keys = []; //必填选项
        const { location, back, positive } = this.data;
        keys = ["adminName", "phone", "addressDesc", "merchantName"]; //必填选项

        const result = keys.every((item) => values[item]);
        if (!result) {
            wx.showToast({
                title: "还有选项没填哦",
                icon: "none",
            });
            return false;
        }
        if (location.latitude == 0) {
            wx.showToast({
                title: "所在位置还没选哦",
                icon: "none",
            });
            return false;
        }
        return true;
    },
    // 参数处理
    getParams(values) {
        const {
            location,
            findMerchantCityInfoList,
            mapName,
            mapDetail,
            doorPhoto,
            storePhoto,
        } = this.data;
        const userInfo = wx.getStorageSync("userInfo");
        const cityId = findMerchantCityInfoList.find(
            (item) => item.cityName == this.data.location.city
        ) || {id: 0};
        const doorPhotoList = doorPhoto.filter(item => {
            if(!item.error){
                return item;
            }
        }).map(item => { return item.url })
        const storePhotoList = storePhoto.filter(item => {
            if(!item.error){
                return item;
            }
        }).map(item => { return item.url })
        values.addressDesc = mapName + mapDetail;
        let defaultData = {
            addressDesc: "",
            adminName: "",
            applyStatus: 0,
            cityId: cityId.id || 0,
            distance: 0,
            // doorPhoto: JSON.stringify(doorPhotoList),
            doorPhoto: doorPhotoList,
            id: 0,
            isAttestation: true,
            lat: location.latitude,
            lon: location.longitude,
            memberId: userInfo.id || 0,
            merchantCategory: 0,
            merchantCategoryName: "",
            merchantDesc: "",
            merchantName: "",
            phone: "",
            sort: 0,
            status: true,
            // storePhoto: JSON.stringify(storePhotoList),
            storePhoto: storePhotoList,
        };
        return Object.assign(defaultData, values);
    },
    // 计算说明字数
    descriptionTotal(e) {
        const num = e.detail.value.length;
        this.setData({
            numTotal: num,
        });
    },
    // 图片
    chooseImage: function (e) {
        var that = this;
        wx.chooseImage({
            count: 1,
            sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ["album", "camera"], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                that.setData({
                    files: that.data.files.concat(res.tempFilePaths),
                });
            },
        });
    },
    previewImage: function (e) {
        wx.previewImage({
            current: e.currentTarget.id, // 当前显示图片的http链接
            urls: this.data.files, // 需要预览的图片http链接列表
        });
    },
    selectFile(files) {
        console.log("files", files);
        // 返回false可以阻止某次文件上传
    },
    uplaodFile(files) {
        console.log("upload files", files);
        const { tempFilePaths } = files;
        // 文件上传的函数，返回一个promise
        return new Promise((resolve, reject) => {
            const img_list = [],
                error_list = [];
            let count = 0;
            for (let i = 0; i < tempFilePaths.length; i++) {
                wx.uploadFile({
                    url: api.leader.uploadImageUrl, //仅为示例，非真实的接口地址
                    filePath: tempFilePaths[i],
                    name: "file",
                    // formData: {
                    //   'user': type
                    // },
                    success(result) {
                        wx.hideLoading();
                        count++;
                        if (result.statusCode === 413) {
                            // reject("图片太大了");
                            wx.showToast({
                                title: "图片太大了",
                                icon: "error",
                            });
                            error_list[i] = tempFilePaths[i];
                            img_list.push(tempFilePaths[i]);
                        } else {
                            result.data = JSON.parse(result.data);
                            const data = result.data.message;
                            img_list.push(data);
                        }
                        console.log("img_list", img_list);
                        if (count === tempFilePaths.length) {
                            if (img_list.length > 0) {
                                resolve({
                                    urls: img_list,
                                    error: error_list
                                });
                            } else {
                                reject();
                            }
                        }
                    },
                });
            }
        });
    },
    uploadError(e) {
        console.log("upload error", e.detail);
    },
    uploadSuccess(e) {
        const type = e.target.dataset.type,
            urls = e.detail.urls,
            error_list = e.detail.error;
        console.log("upload success", e.detail);
        console.log("upload success", type);
        const data = this.data[type];
        let list = urls.map((item, index) => {
            let obj = {};
            obj.url = item;
            if(error_list[index]){
                obj.error = true
            }
            return obj;
        });
        this.setData({
            [type]: data.concat(list),
        });
    },
    handleDelete(e) {
        const type = e.target.dataset.type;
        const { index, item } = e.detail;
        console.log("e.detail", e.detail);
        let pics = this.data[type];
        pics.splice(index, 1);
        this.setData({
            [type]: pics,
        });
    },
    findMerchantCityInfoListData() {
        util.request(
            api.surroundings.findMerchantCityInfoList,
            {},
            "POST"
        ).then((res) => {
            console.log("res");
            this.setData({
                findMerchantCityInfoList: res.result,
            });
        });
    },
});
